import "babel-polyfill";
import tpl from './tpl/wrapper.tpl';
import itemTpl from './tpl/item.tpl';
import tools from '../../utils/tools';
import { ShowBoard } from '../../components/show_board';
import './index.scss';

class Tab{
    constructor(el,fieldDatas,phoneDatas){
        this.name = 'tab';
        this.$el = el;
        this.phoneDatas = phoneDatas;
        this.fieldDatas = fieldDatas;
        this.cache = {};

    }
    async init(){
       await this.render();
             this.bindEvent();
    }
  async render(){
        var list = "";
           this.fieldDatas.forEach((item,idx)=>{
                list += tools.tplReplace(itemTpl(),{
                    field:item.field,
                    series_name:item.series_name
                })

           });
        await this.$el.append(tools.tplReplace(tpl(),{list}));
    }
    bindEvent(){
        const $oTab = $('.J_tab'),
              $board = $('.J_board'),
              $inputSearch = $('#J_search'),
              oShowBoard = new ShowBoard()

              $oTab.on('click','.tab-item',{$board, oShowBoard, $oTab},$.proxy(this.tabClcik,this));
    }
    tabClcik(e){
        const data = e.data,
              $board = data.$board,
              oShowBoard = data.oShowBoard,
              tar = e.target,
              $tar = $(tar),
              tagName = tar.tagName.toLowerCase();
            //   console.log($tar);
              if(tagName === "a"){
               const field = $tar.attr('data-field');
               this.tabChange($tar);
               this.appendList($board, oShowBoard,field);
              }
    }
    tabChange($target){
        $target.parent().addClass('current').
                         siblings().removeClass('current');
    }
    appendList($board,oShowBoard,field,keyword){
        if(keyword){

        }else{
            if(!this.cache[field]){
                this.cache[field]=oShowBoard.makeList(this.filterDatas(this.phoneDatas, field))
            }
             $board.html(this.cache[field]);
        }
    }
    filterDatas(phoneDatas,field,keyword){
           return phoneDatas.filter((item,idx)=>{
               if(keyword){
                const phone_name = item.phone_name.toLowerCase(),
                slogan = item.slogan.toLowerCase();
                 keyword = keyword.toLowerCase();
                 return phone_name.includes(keyword) || slogan.includes(keyword);
               }else{
                switch(field){
                    case 'all':
                        return true;
                        break;
                    default:
                        return item.field == field;
                        break;
                    }   
               }
                 
            
            });
        }
    }
    


export{ Tab } 